package com.zhilianbao.leyaogo.ui.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bql.convenientlog.CLog;
import com.bql.sharesdk.utils.ShareUtil;
import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.bql.utils.ThreadPool;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.listener.OnLoginListener;
import com.zhilianbao.leyaogo.model.response.UserLoginInfo;
import com.zhilianbao.leyaogo.ui.activity.base.BaseOkHttpActivity;
import com.zhilianbao.leyaogo.utils.LogicCodeBlock;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.widgets.AwesomeEditTextView;
import com.zlb.lxlibrary.service.LeXiuInitService;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.zhilianbao.ice.service.IceService;
import okhttp3.Call;
import okhttp3.Response;


/**
 * 登录页面
 * Created by gyt on 2016/11/8
 */
public class LoginActivity extends BaseOkHttpActivity {


    @BindView(R.id.edt_login_userName)
    AwesomeEditTextView mEdtUserName;
    @BindView(R.id.edt_login_password)
    AwesomeEditTextView mEdtPassword;
    @BindView(R.id.tv_login)
    TextView mTvLogin;
    @BindView(R.id.tv_forget_password)
    TextView mTvForgetPassword;
    @BindView(R.id.iv_login_QQ)
    ImageView mIvLoginQQ;
    @BindView(R.id.iv_login_WeChat)
    ImageView mIvLoginWeChat;
    @BindView(R.id.ll_third_login)
    LinearLayout mLlThirdLogin;
    @BindView(R.id.tv_register)
    TextView mTvRegister;
    private String mUserName;
    private String mPassword;

    private int logicState;
    // QQ昵称
    private static String NICK_NAME = "nickname";
    // QQ100x100尺寸的头像
    private static String FIGURE_URL = "figureurl_2";

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_login;
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        initToolbar(getString(R.string.password_login));
        if (getIntent().getExtras() != null) {
            logicState = getIntent().getExtras().getInt(IntentConfig.LOGIC_CODE, 0);
        }
        // 初始化shareSDK
        ShareUtil.initSDK(this);
        mEdtUserName.addTextChangedListener(MyTextWatcher);
        mEdtPassword.addTextChangedListener(MyTextWatcher);
        mTvLogin.setEnabled(false);
        mEdtUserName.setText(Utils.getUserLoginName());

        //        Drawable drawableQQ = mIvLoginQQ.getDrawable();
        //        Drawable drawableWeChat = mIvLoginWeChat.getDrawable();
        //        mIvLoginQQ.setImageDrawable(Utils.tintDrawable(drawableQQ, ColorStateList.valueOf(Color.WHITE)));
        //        mIvLoginWeChat.setImageDrawable(Utils.tintDrawable(drawableWeChat, ColorStateList.valueOf(Color.BLUE)));
    }


    @OnClick({R.id.iv_login_WeChat, R.id.iv_login_QQ, R.id.tv_login, R.id.tv_register, R.id.tv_forget_password})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_login:
                loginMobile();
                break;
            case R.id.tv_register:
                //                Utils.startActivity(this, RegisterActivity.class);
                Utils.gotoLogin(logicState);
                finish();
                break;
            case R.id.tv_forget_password:
                Utils.startActivity(this, ForgetPwdActivity.class);
                break;
            case R.id.iv_login_WeChat:
                loginWeChat();
                break;
            case R.id.iv_login_QQ:
                loginQQ();
                break;
        }

    }

    /**
     * 手机号登录
     */
    private void loginMobile() {
        if (mUserName.length() != 11) {
            XToastUtils.showShortToast(R.string.wrong_phone_length);
            return;
        }

        if (!Utils.isPhoneNumber(mUserName)) {
            XToastUtils.showShortToast(R.string.wrong_phone_format);
            return;
        }

        if (!CheckUtils.isMobilePhone(mUserName)) {
            XToastUtils.showShortToast(R.string.invalid_phone_number);
            return;
        }
        AccountApi.login(this, 0, mUserName, mPassword, new DialogCallback<UserLoginInfo>(this, getResources().getString(R.string.hint_logining)) {

            @Override
            public void onSuccess(UserLoginInfo userLoginInfo, Call call, Response response) {
                if (userLoginInfo == null) {
                    XToastUtils.showShortToast(R.string.unregistered_phone);
                } else {
                    //登录成功保存用户信息
                    Utils.putUserLoginInfo(userLoginInfo);
                    Utils.putUserLoginName(mUserName);
                    XToastUtils.showShortToast(R.string.login_suc);
                    //登录成功初始化ICE
                    IceService.getInstance().initIce();
                    //                    Utils.registerPush();
                    LeXiuInitService.getInstance().onLegoLoginSuccess(userLoginInfo.getUserId() + "", userLoginInfo.getUserAlias(), Utils.returnUrlShow(userLoginInfo.getUserPic()), userLoginInfo.getTokenId(), Utils.getSupplierId() + "");
                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_LOGIN_SUCCESS));
                    ThreadPool.postOnUiDelayed(() -> LogicCodeBlock.create().dispatchLogicCode(logicState), 500);
                    finish();
                }
            }

        });
    }

    private void loginWeChat() {
        Utils.thirdPartyLogin(this, Wechat.NAME, new OnLoginListener() {
            @Override
            public boolean onLogin(String platform, HashMap<String, Object> res) {
                CLog.i("onLogin");
                //遍历Map
                Iterator ite =res.entrySet().iterator();
                while (ite.hasNext()) {
                    Map.Entry entry = (Map.Entry)ite.next();
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
//
//                    if (TextUtils.equals(key, NICK_NAME)) {
//                        String nickName = value;
//                    }
//                    if (TextUtils.equals(key, FIGURE_URL)) {
//                        String figureUrl = value;
//                    }

                    setUserData();
                    CLog.i(key+"：：： "+value);
                }
                return false;
            }
        });
    }

    public void loginQQ() {
        Utils.thirdPartyLogin(this, QQ.NAME, new OnLoginListener() {
            @Override
            public boolean onLogin(String platform, HashMap<String, Object> res) {
                //遍历Map
                Iterator ite =res.entrySet().iterator();
                while (ite.hasNext()) {
                    Map.Entry entry = (Map.Entry)ite.next();
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();

                    if (TextUtils.equals(key, NICK_NAME)) {
                        String nickName = value;
                    }
                    if (TextUtils.equals(key, FIGURE_URL)) {
                        String figureUrl = value;
                    }

                    setUserData();
                    CLog.i(key+"：：： "+value);
            }
                return false;
            }
        });
    }

    /**
     * 设置用户数据
     */
    private void setUserData() {

    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        // 注册手机号存在时，从RegisterActivity跳转回来
        if (eventManager.getEventCode() == LeEventCode.MSG_CODE_BACK_TO_LOGIN_ACTIVITY) {
            mEdtUserName.setText(Utils.getUserLoginName());
        } else if (eventManager.getEventCode() == LeEventCode.MSG_CODE_LOGIN_SUCCESS) {
            finish();
        }
    }

    private TextWatcher MyTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            enableLoginBtn();
        }
    };

    private void enableLoginBtn() {
        mUserName = mEdtUserName.getText().toString();
        mPassword = mEdtPassword.getText().toString();
        mTvLogin.setEnabled(!TextUtils.isEmpty(mUserName) && !TextUtils.isEmpty(mPassword));
    }

    @Override
    protected boolean isStatusDarkMode() {
        return true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        mEdtUserName.clearFocus();
        mEdtPassword.clearFocus();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (MyTextWatcher != null) {
            mEdtPassword.removeTextChangedListener(MyTextWatcher);
            mEdtUserName.removeTextChangedListener(MyTextWatcher);
            MyTextWatcher = null;
        }
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return true;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return TransitionMode.FADE;
    }

    @Override
    public void leftContainerClick() {
        super.leftContainerClick();
        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_CLICK_NOT_LOGIN_BACK));
    }
}
